<template>
	<view class="address-container">
		<!-- 自定义导航栏 -->
		<u-navbar
			title="收货地址"
			:autoBack="true"
			bgColor="#ffffff"
			:fixed="true"
			:placeholder="true"
			:safeAreaInsetTop="true"
		></u-navbar>
		
		<!-- 地址列表 -->
		<view class="address-list" v-if="addressList.length > 0">
			<view 
				class="address-item" 
				v-for="(item, index) in addressList" 
				:key="index"
				@click="selectAddress(item)"
			>
				<view class="address-info">
					<view class="user-info">
						<text class="name">{{item.name}}</text>
						<text class="phone">{{item.phone}}</text>
						<text class="tag" v-if="item.isDefault">默认</text>
					</view>
					<view class="address-detail">
						{{item.province}} {{item.city}} {{item.district}} {{item.detailAddress}}
					</view>
				</view>
				<view class="address-actions">
					<view class="action-item" @click.stop="setDefaultAddress(item)" v-if="!item.isDefault">
						<u-icon name="checkmark-circle" size="40rpx" color="#ff5722"></u-icon>
					</view>
					<view class="action-item" @click.stop="editAddress(item)">
						<u-icon name="edit-pen" size="40rpx" color="#666"></u-icon>
					</view>
					<view class="action-item" @click.stop="deleteAddress(item)">
						<u-icon name="trash" size="40rpx" color="#666"></u-icon>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空地址提示 -->
		<view class="empty-address" v-else>
			<image class="empty-image" src="/static/images/empty-address.png" mode="aspectFit"></image>
			<text class="empty-text">您还没有收货地址</text>
		</view>
		
		<!-- 新增地址按钮 -->
		<view class="add-address-btn">
			<u-button 
				type="primary" 
				text="+ 新增地址" 
				@click="goToAddAddress"
				shape="circle"
			></u-button>
		</view>
	</view>
</template>

<script>
import { get, del, put } from '@/utils/request'
import { getUserId, getToken, isLoggedIn, goToLogin } from '@/utils/auth'

export default {
	data() {
		return {
			addressList: [],
			isFromOrder: false // 是否从订单页面跳转而来
		}
	},
	onLoad(options) {
		// 检查是否从订单页面跳转而来
		if (options.from === 'order') {
			this.isFromOrder = true;
		}

		// 获取地址列表
		this.getAddressList();
	},
	onShow() {
		// 返回该页时刷新
		this.getAddressList();
	},
	methods: {
		// 解析 JWT 的 payload，尝试从 token 获取 user_id
		parseUserIdFromToken() {
			try {
				const token = getToken();
				if (!token) return null;
				const parts = token.split('.')
				if (parts.length !== 3) return null;
				// Base64Url 解码
				const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
				const padded = base64 + '==='.slice((base64.length + 3) % 4);
				const json = decodeURIComponent(escape(atob(padded)));
				const payload = JSON.parse(json);
				const id = payload.user_id || payload.userId || payload.uid;
				const n = Number(id);
				return Number.isNaN(n) ? null : n;
			} catch (e) {
				return null;
			}
		},

		// 兜底调用后端获取当前用户信息，提取 userId
		async fetchUserIdFromServer() {
			try {
				const res = await get('/user1/info');
				const data = res?.data || {};
				const id = data.userId || data.id || data.user_id;
				const n = Number(id);
				return Number.isNaN(n) ? null : n;
			} catch (e) {
				return null;
			}
		},

		// 获取地址列表
		async getAddressList() {
			if (!isLoggedIn()) { goToLogin(); return; }
			try {
				// 1) 本地 userId
				let userIdNum = Number(getUserId());
				// 2) token 解析
				if (Number.isNaN(userIdNum)) userIdNum = this.parseUserIdFromToken() ?? NaN;
				// 3) 后端兜底
				if (Number.isNaN(userIdNum)) userIdNum = (await this.fetchUserIdFromServer()) ?? NaN;
				if (Number.isNaN(userIdNum)) { uni.showToast({ title: '未获取到用户ID，请重新登录', icon: 'none' }); return; }
				// 调用后端按用户ID查询地址列表接口
				const res = await get(`/address/list`, { userId: userIdNum });
				// 接口返回为 AjaxResult，数据在 res.rows 中
				const list = res?.rows || [];
				this.addressList = list.map(item => ({
					id: item.id,
					name: item.userName,
					phone: item.phone,
					province: item.province,
					city: item.city,
					district: item.county,
					detailAddress: item.content,
					isDefault: item.isDefault || false
				}));
			} catch (e) {
				uni.showToast({ title: '获取地址失败', icon: 'none' });
			}
		},
		
		// 选择地址（从订单页面跳转而来时使用）
		selectAddress(address) {
			if (this.isFromOrder) {
				// 将选中的地址传回订单页面
				uni.$emit('addressSelected', address);
				// 触发地址变化事件，通知其他页面更新
				uni.$emit('addressChanged');
				uni.navigateBack();
			}
		},
		
		// 编辑地址
		editAddress(address) {
			uni.navigateTo({
				url: `/pages/add-address/add-address?id=${address.id}`
			});
		},
		
		// 设置默认地址
		async setDefaultAddress(address) {
			try {
				// 调用后端接口设置默认地址
				await put('/address', { 
					id: address.id, 
					isDefault: true 
				});
				
				uni.showToast({ 
					title: '设置默认地址成功', 
					icon: 'success' 
				});
				
				// 刷新地址列表
				this.getAddressList();
				
				// 触发地址变化事件，通知其他页面更新
				uni.$emit('addressChanged');
				
			} catch (e) {
				uni.showToast({ 
					title: '设置默认地址失败', 
					icon: 'none' 
				});
			}
		},
		
		// 删除地址
		deleteAddress(address) {
			uni.showModal({
				title: '提示',
				content: '确定要删除该地址吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await del(`/address/${address.id}`);
							uni.showToast({ title: '删除成功', icon: 'success' });
							this.getAddressList();
						} catch (e) {
							uni.showToast({ title: '删除失败', icon: 'none' });
						}
					}
				}
			});
		},
		
		// 跳转到新增地址页面
		goToAddAddress() {
			uni.navigateTo({
				url: '/pages/add-address/add-address'
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.address-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.address-list {
	padding: 24rpx;
}

.address-item {
	background-color: #ffffff;
	border-radius: 16rpx;
	padding: 32rpx;
	margin-bottom: 24rpx;
	display: flex;
	justify-content: space-between;
	border: 1rpx solid #f2f3f5;
	box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.04);
	transition: transform 0.12s ease, box-shadow 0.2s ease;
	overflow: hidden;
}

.address-item:active {
	transform: scale(0.98);
	box-shadow: 0 4rpx 14rpx rgba(0, 0, 0, 0.06);
}

.address-info {
	flex: 1;
}

.user-info {
	display: flex;
	align-items: center;
	margin-bottom: 18rpx;
}

.name {
	font-size: 34rpx;
	font-weight: bold;
	margin-right: 20rpx;
}

.phone {
	font-size: 28rpx;
	color: #8c8c8c;
	margin-right: 20rpx;
}

.tag {
	background-color: rgba(255, 87, 34, 0.1);
	color: #ff5722;
	font-size: 22rpx;
	padding: 6rpx 12rpx;
	border-radius: 999rpx;
	border: 1rpx solid #ff5722;
}

.address-detail {
	font-size: 28rpx;
	color: #555;
	line-height: 1.6;
	margin-top: 4rpx;
	display: -webkit-box;
	line-clamp: 2;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
	word-break: break-word;
}

.address-actions {
	display: flex;
	flex-direction: column;
	justify-content: center;
	margin-left: 16rpx;
}

.action-item {
	width: 64rpx;
	height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	background-color: #f7f8fa;
	margin: 8rpx 0;
	transition: background-color 0.2s ease, transform 0.12s ease;
}

.action-item:active {
	background-color: #eee;
	transform: scale(0.96);
}

.empty-address {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding-top: 200rpx;
}

.empty-image {
	width: 220rpx;
	height: 220rpx;
	margin-bottom: 26rpx;
	opacity: 0.9;
}

.empty-text {
	font-size: 30rpx;
	color: #8c8c8c;
}

.add-address-btn {
	position: fixed;
	bottom: 30rpx;
	left: 30rpx;
	right: 30rpx;
	padding-bottom: env(safe-area-inset-bottom);
	filter: drop-shadow(0 6rpx 14rpx rgba(0, 0, 0, 0.08));
}

/* 按钮视觉增强（深度选择器覆盖 u-button 默认样式） */
::v-deep .u-button {
	background-image: linear-gradient(135deg, #ff7a45 0%, #ff5722 100%) !important;
	border: none !important;
	box-shadow: 0 8rpx 20rpx rgba(255, 87, 34, 0.28) !important;
}

</style>